import { defineStore } from 'pinia'
import request from '@/utils/request'
import router from '@/router'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
    token: localStorage.getItem('token') || null,
    permissions: JSON.parse(localStorage.getItem('permissions')) || {
      modules: [],
      actions: {}
    },
    isLoginPending: false,
    userRole: localStorage.getItem('userRole') || '',
  }),

  getters: {
    isLoggedIn: (state) => !!state.token && !!state.userInfo,
    getUserInfo: (state) => state.userInfo,
    getUserRole: (state) => state.userRole,
    /**
     * 检查是否有特定模块权限
     */
    hasModulePermission: (state) => (module) => {
      return state.permissions?.modules?.includes(module) || false
    },
    /**
     * 检查是否有特定操作权限
     */
    hasActionPermission: (state) => (module, action) => {
      const moduleActions = state.permissions?.actions?.[module] || []
      return moduleActions.includes(action)
    },
    hasPermission: (state) => (module, action) => {
      if (!state.permissions || !state.permissions.actions) return false;
      return state.permissions.actions[module]?.includes(action);
    },
    hasModule: (state) => (module) => {
      if (!state.permissions || !state.permissions.modules) return false;
      return state.permissions.modules.includes(module);
    }
  },

  actions: {
    /**
     * 设置用户信息
     * @param {Object} userInfo - 用户信息对象
     */
    setUserInfo(userInfo) {
      console.log('设置用户信息:', userInfo)
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },

    /**
     * 设置token
     * @param {string} token - 用户token
     */
    setToken(token) {
      console.log('设置Token:', token ? `${token.substring(0, 15)}...` : 'null')
      this.token = token
      localStorage.setItem('token', token)
    },

    /**
     * 设置权限
     * @param {Object} permissions - 权限对象
     */
    setPermissions(permissions) {
      console.log('设置权限:', permissions)
      this.permissions = permissions
      localStorage.setItem('permissions', JSON.stringify(permissions))
    },

    /**
     * 设置用户角色
     * @param {string} role - 用户角色
     */
    setUserRole(role) {
      this.userRole = role
      localStorage.setItem('userRole', role)
    },

    /**
     * 获取用户权限
     * @returns {Promise} 权限获取结果的Promise
     */
    async fetchPermissions() {
      console.log('获取权限 - 状态检查:', { 
        isLoggedIn: this.isLoggedIn,
        hasToken: !!this.token, 
        hasUserInfo: !!this.userInfo,
        userRole: this.userRole
      })
      
      try {
        if (!this.token) {
          console.warn('获取权限失败: 缺少token')
          return Promise.reject(new Error('缺少token'))
        }
        
        console.log('开始获取权限...')
        this.isLoginPending = true
        
        // 临时解决方案：使用模拟权限数据，跳过API调用
        // const response = await request.get('/api/admin/users/permissions/')
        
        // 模拟API响应
        const mockResponse = {
          status: 'success',
          data: {
            permissions: {
              modules: ['dashboard', 'user', 'college', 'teacher', 'class', 'resource', 'system'],
              actions: {
                user: ['view', 'add', 'edit', 'delete'],
                college: ['view', 'add', 'edit', 'delete'],
                teacher: ['view', 'add', 'edit', 'delete'],
                class: ['view', 'add', 'edit', 'delete'],
                resource: ['view', 'add', 'edit', 'delete'],
                system: ['view', 'edit']
              }
            }
          }
        }
        
        this.isLoginPending = false
        
        console.log('模拟权限响应:', mockResponse)
        
        if (mockResponse && mockResponse.status === 'success' && mockResponse.data) {
          this.setPermissions(mockResponse.data.permissions)
          return Promise.resolve(mockResponse.data.permissions)
        } else {
          console.warn('权限响应格式异常:', mockResponse)
          return Promise.reject(new Error('权限响应格式异常'))
        }
      } catch (error) {
        this.isLoginPending = false
        console.error('获取权限失败:', error)
        return Promise.reject(error)
      }
    },

    /**
     * 登录成功后的处理
     * @param {Object} loginData - 登录响应数据
     */
    async handleLoginSuccess(loginData) {
      console.log('处理登录成功:', loginData)
      
      // 保存token和用户信息
      this.setToken(loginData.token)
      this.setUserInfo({
        username: loginData.username,
        role: loginData.role,
        avatar: loginData.avatar || '',
        id: loginData.id
      })
      this.setUserRole(loginData.role)
      
      // 获取权限信息
      try {
        await this.fetchPermissions()
        console.log('权限获取成功，准备导航至管理页面')
        
        // 根据角色导航到相应页面
        if (this.userRole.includes('admin')) {
          router.replace('/admin/home')
          ElMessage.success('管理员登录成功')
        } else if (this.userRole === 'teacher') {
          router.replace('/teacher/home')
          ElMessage.success('教师登录成功')
        } else if (this.userRole === 'student') {
          router.replace('/student/home')
          ElMessage.success('学生登录成功')
        } else {
          console.warn('未知角色:', this.userRole)
          router.replace('/admin/home')
          ElMessage.success('登录成功')
        }
      } catch (err) {
        console.error('权限获取失败:', err)
        ElMessage.warning('登录成功，但权限获取失败')
        // 即使权限获取失败，也尝试导航
        router.replace('/admin/home')
      }
    },

    /**
     * 退出登录
     */
    logout() {
      this.userInfo = null
      this.token = null
      this.permissions = {
        modules: [],
        actions: {}
      }
      this.userRole = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('permissions')
      localStorage.removeItem('userRole')
      
      // 导航到登录页
      router.push('/login')
    }
  }
})
